package com.chzc.sys.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chzc.po.User;
import com.chzc.sys.req.UserREQ;
import com.chzc.sys.mapper.UserMapper;
import com.chzc.sys.service.IUserService;
import com.chzc.util.Result;
import com.chzc.util.enums.StatusCode;
import com.chzc.vo.UserRegister;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author CV大魔王
 * @since 2021-05-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Result login(String username, String password) {
        User user = findUserByLogin(username,password);

        // 调用sa-token标记登录信息
        if (user != null) {
            StpUtil.setLoginId(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return new Result(true,
                    StatusCode.JWT_LOGIN_SUCCESS.getCode(),
                    StatusCode.JWT_LOGIN_SUCCESS.getMessage(),
                    tokenInfo.getTokenValue());
        }
        // 登录失败
        return new Result(false,
                StatusCode.JWT_LOGIN_FAIL.getCode(),
                StatusCode.JWT_LOGIN_FAIL.getMessage());
    }

    @Override
    public String loginTest(String username, String password) {
        User user = findUserByLogin(username,password);
        if (user != null) {
            StpUtil.setLoginId(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return tokenInfo.getTokenValue();
        }
        return null;
    }

    @Cacheable(value = {"user"},key = "#root.methodName+'_'+#root.method+'_'+#username+''+#password")
    public User findUserByLogin(String username, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public User getUserInfo() {
        String loginId = (String) StpUtil.getLoginId();
        User user = baseMapper.selectById(loginId);
        user.setPassword("");
        return user;
    }

    @Override
    public Result register(UserRegister user) {
        // 判断账号是否未注册
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0){
            return new Result(false,StatusCode.REGISTER_FAIL.getCode(),StatusCode.REGISTER_FAIL.getMessage());
        }

        // 添加用户
        User userInfo = new User();
        userInfo.setUsername(user.getUsername());
        userInfo.setImageUrl(user.getImageUrl());
        userInfo.setMobile(user.getMobile());
        userInfo.setNickName(user.getNickName());
        userInfo.setPassword(user.getPassword());
        userInfo.setCreateDate(new Date());
        userInfo.setIsEnabled(1);
        baseMapper.insert(userInfo);

        // 添加用户角色关联关系
        baseMapper.insertUserRole(IdWorker.getId()+"",userInfo.getId(),"3");
        return null;
    }


    @Override
    @Cacheable(value = {"user"},key = "#root.methodName+'_'+#req.current+'_'+#req.size+'_'+#req.username+'_'+#req.mobile")
    public IPage<User> queryPage(UserREQ req) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        // 条件查询
        if (StringUtils.isNotEmpty(req.getUsername())) {
            wrapper.like("username", req.getUsername());
        }
        if (StringUtils.isNotEmpty(req.getMobile())) {
            wrapper.like("mobile", req.getMobile());
        }
        wrapper.orderByDesc("create_date");
        return baseMapper.selectPage(req.getPage(), wrapper);
    }


    @Override
    @Cacheable(value = {"user"},key = "#root.methodName+'_'+#root.method+'_'+#id")
    public List<String> findRoleIdsById(String id) {
        return baseMapper.findRoleIdsById(id);
    }


    @Transactional
    @Override
    @Caching(evict = {
            @CacheEvict(value = "role",allEntries = true),
            @CacheEvict(value = "user",allEntries = true),
            @CacheEvict(value = "menu",allEntries = true)
    })
    public Result saveUserRole(String userId, List<String> roleIds) {
        // 1. 先删除用户角色关系表数据
        baseMapper.deleteUserRoleByUserId(userId);
        // 2. 再保存新的用户角色关系数据
        if (CollectionUtils.isNotEmpty(roleIds)) {
            baseMapper.saveUserRole(userId, roleIds);
        }
        return Result.addSuccess();
    }


    @Override
    @Caching(evict = {
            @CacheEvict(value = "role",allEntries = true),
            @CacheEvict(value = "user",allEntries = true),
            @CacheEvict(value = "menu",allEntries = true)
    })
    public Result deleteById(String id) {
        // 将 `is_enabled` 状态更新为 0 表示删除
        User user = baseMapper.selectById(id);
        if (user == null) {
            return Result.buildError("用户不存在，删除失败");
        }
        user.setIsEnabled(0); // 0 删除，1 可用
        baseMapper.updateById(user);
        return Result.deleteSuccess();
    }




    @Transactional
    @Override
    @CacheEvict(value = "user",allEntries = true)
    public Result update(User user) {
        // 1. 查询原用户信息
        User userOld = baseMapper.selectById(user.getId());
        if (userOld == null) {
            return Result.buildError("更新的用户不存在");
        }
        // 2. 更新用户信息表
        baseMapper.updateById(user);
        return Result.editSuccess();
    }

    @Override
    @Cacheable(value = {"user"},keyGenerator = "springCacheDefaultKeyGenerator")
    public Integer getUserTotal() {
        // 帐户是否可用(1 可用，0 删除用户)
        return baseMapper.selectCount(new QueryWrapper<User>().eq("is_enabled", 1));
    }


    @Cacheable(value = {"user"},key = "#root.methodName+'_'+#root.method+'_'+#username")
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Cacheable(value = {"user"},key = "#root.methodName+'_'+#root.method+'_'+#id")
    public User findUserById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    @Cacheable(value = {"user"},keyGenerator = "springCacheDefaultKeyGenerator")
    public List<String> findAllId() {
        return baseMapper.findAllUsername();
    }


}
